package com.ideabove.radio.module;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import com.ideabove.adapter.FolderEditAdapter;
import com.ideabove.data.Folder;
import com.ideabove.network.NetWorkManager;
import com.ideabove.radio.MainActivity;
import com.ideabove.radio.R;
import com.ideabove.util.ConnectThread;
import com.ideabove.util.img.ImageLoader;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.PorterDuff.Mode;
import android.graphics.Typeface;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ScaleXSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class FolderEditMd extends ModuleAbs {
	
	public void init(MainActivity activity){
		super.init(activity);
	}
	
	public interface ShowFolersCallback{
		public void callback(ListView listView);
	}
	
	
	public void showFolderEditList(final ShowFolersCallback callback){
		ModuleAbs.showProgressDialog(activity, "", "잠시만 기다려주세요...");
		
		// 엑티비티에 뷰를 세팅한다.
		activity.setCurrentMoudle(this);
		View view = (View)activity.findViewById(R.id.flipper_layout);
		view.setVisibility(View.VISIBLE);
		
		LinearLayout studioMain = (LinearLayout)activity.findViewById(R.id.studio_main);		
		
		LayoutInflater layoutInflater = (LayoutInflater) 
        activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View viewToInsert = (View)layoutInflater.inflate(R.layout.studio_folder_edit, null);	
		studioMain.removeAllViews();
		studioMain.addView(viewToInsert); 
		
		int timeout = 3;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
			
			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				ModuleAbs.hideProgressDialog();
				AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
				ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
				ab.setPositiveButton("ok", null);  
				ab.show();
			}
			
			@Override
			public void sucess(Object result){
				ModuleAbs.hideProgressDialog();
				
				
				SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE);
				String fbPicUrl 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_PIC_URL, "");
				String fbFirstNm 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_FIRST_NM, "");
				String fbLastNm 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_LAST_NM, "");
				String clubName 	= prefs.getString(FacebookMd.PREFERENCE_USER_CLUB_NAME, "");
				
				ImageView user_folder_pic = (ImageView)activity.findViewById(R.id.user_folder_edit_pic);
				ImageLoader.download(fbPicUrl, user_folder_pic);	
				
				TextView user_name = (TextView)activity.findViewById(R.id.folder_edit_user_name);
				user_name.setText(fbFirstNm + " " + fbLastNm);
								
				TextView folder_club_name = (TextView)activity.findViewById(R.id.folder_club_name);
				folder_club_name.setText(clubName);
				
				FrameLayout btn_top_left_btn_wrap = (FrameLayout)activity.findViewById(R.id.btn_top_left_btn_wrap);
				btn_top_left_btn_wrap.setVisibility(View.VISIBLE);
				
				LinearLayout folder_user_profile_edit = (LinearLayout)activity.findViewById(R.id.folder_user_profile_edit);
				folder_user_profile_edit.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						if(event.getAction() == MotionEvent.ACTION_UP){
							activity.userProfileEditMd.showUserProfileEdit();
						}
						
						return true;
					}
				});
				
				
				
				TextView btn_top_right_text = (TextView)activity.findViewById(R.id.btn_top_right_text);
				btn_top_right_text.setText("Ok");				
				ImageView btn_top_right_img = (ImageView)activity.findViewById(R.id.btn_top_right_img);
				btn_top_right_img.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
																				
							// code
							activity.folderMd.showFolderList();
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
				
				TextView btn_top_left_text = (TextView)activity.findViewById(R.id.btn_top_left_text);
				btn_top_left_text.setText("Cancel");
				ImageView btn_top_left_img = (ImageView)activity.findViewById(R.id.btn_top_left_img);
				btn_top_left_img.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
																				
							// code
							activity.folderMd.showFolderList();
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
				
				ArrayList<Folder> folderArr = (ArrayList<Folder>)result;				
				ListAdapter adapter = new FolderEditAdapter(activity.getApplicationContext(),folderArr, activity);
				
				ListView folder_list = (ListView)activity.findViewById(R.id.listv_edit_folders);				
				folder_list.setAdapter(adapter);
				
				
				if(callback != null){
					callback.callback(folder_list);
				}		
				
				
				
				// 새로운 폴더 추가하기
				ImageView folder_add_new_btn = (ImageView)activity.findViewById(R.id.folder_add_new_btn);
				folder_add_new_btn.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
							
							String comment = " 폴더명을 넣어주세요.";
							SpannableStringBuilder ssBuilser = new SpannableStringBuilder();
							ssBuilser.append(comment);
							
							StyleSpan span = new StyleSpan(Typeface.NORMAL);
							ScaleXSpan span1 = new ScaleXSpan(0.7f);
							ssBuilser.setSpan(span, 0, comment.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
							ssBuilser.setSpan(span1, 0, comment.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);


							// 폴더이름 추가 다이얼로그
							LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

							final View layout = inflater.inflate(R.layout.studio_folder_name_popup,(ViewGroup) activity.findViewById(R.id.folder_add_popup));													
							AlertDialog.Builder aDialog = new AlertDialog.Builder(activity);
							aDialog.setTitle(ssBuilser);
							aDialog.setView(layout);											
							aDialog.setPositiveButton("추가", new DialogInterface.OnClickListener() {
								 public void onClick(DialogInterface dialog, int which) {
									 EditText editview = (EditText)layout.findViewById(R.id.folder_add_name_edittext);									 
									 requestFolderAdd(editview.getText().toString());									 
								 }
							});
							aDialog.setNegativeButton("취소", new DialogInterface.OnClickListener() {
								 public void onClick(DialogInterface dialog, int which) {
								 }
							});
							AlertDialog ad = aDialog.create();
							ad.show();
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
								
			}
			
			@Override
			public void threadProcess(ConnectThread resultSet) throws Exception {
				// TODO Auto-generated method stub					
				HttpClient client = NetWorkManager.getHttpConnection();    
				HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);	
				
				// 사용자 정보를 셋팅
				activity.facebookMd.getUserInfo();

				HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/folderListInfo.php");
//					uId : 유저 ID

				String userId = activity.facebookMd.getBonoUserId();
				
				if(userId == null || userId.length() < 1){
					throw new Exception("parameter error");
				}
				
				
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("uId", userId));
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);  

				InputStream in = responsePOST.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{					
					str.append(line);
				}
				
				in.close();					
				String jsonStr = str.toString();
//				Log.e("#########result", "########" + jsonStr);
				
				
				if(jsonStr != null && jsonStr.length() > 0){

					ArrayList<Folder> folderArr = new ArrayList<Folder>();
					JSONObject jsonObj = new JSONObject(jsonStr); 
					JSONArray resultArray = jsonObj.getJSONArray("result");

					for (int i = 0; i < resultArray.length(); i++) {
						Folder folder = new Folder();
						JSONObject jObj = resultArray.getJSONObject(i);
						folder.setFolder_id(jObj.getString("folder_id").toString());
						folder.setTitle(jObj.getString("title").toString());
						folder.setSong_count(jObj.getString("song_count").toString());
						folder.setType(jObj.getString("type").toString());
						folderArr.add(folder);
					}				
					resultSet.setResult(folderArr);	
				}
			}
		}).start(); 
	}
	
	public void requestFolderAdd(final String folderName){
		
		int timeout = 3;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
			
			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
				ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
				ab.setPositiveButton("ok", null);  
				ab.show();
			}
			
			@Override
			public void sucess(Object result){
//				AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
//				ab.setMessage("추가되었습니다.");					
//				ab.setPositiveButton("ok", null);  
//				ab.show();
				
				
				// 리스트 reflash
				showFolderEditList(new FolderEditMd.ShowFolersCallback() {					
					@Override
					public void callback(ListView listView) {
						// TODO Auto-generated method stub
						listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);						
					}
				});
				
				
			}
			
			@Override
			public void threadProcess(ConnectThread resultset) throws Exception {
				// TODO Auto-generated method stub					
				HttpClient client = NetWorkManager.getHttpConnection();    
				HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

				HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/addFolder.php");
				
//				2.	parameter : 
//					a. uId:유저ID 
//					b. fTitle : 폴더명 
//				-Response
//					1. type : plain ( 0 : 실패, 1 : 성공 ) 


				String buserId = activity.facebookMd.getBonoUserId();				
				if(folderName == null){
					throw new Exception("parameter error");
				}
				
				
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("uId", buserId));
				params.add(new BasicNameValuePair("fTitle", folderName));
				
//				Log.e("#########request", "########" + post.getURI().toURL());
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);  

				InputStream in = responsePOST.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{					
					str.append(line);
				}
				in.close();					
				String jsonStr = str.toString();
//				Log.e("#########result", "########" + jsonStr);
				
				if(!"1".equals(jsonStr)){
					throw new Exception("fail");
				}
				
			}
		}).start(); 
	}
	
	
	public void requestFolderRemove(final String folderId){
		
		int timeout = 3;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
			
			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				AlertDialog.Builder ab = new AlertDialog.Builder(activity);
				ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
				ab.setPositiveButton("ok", null);  
				ab.show();
			}
			
			@Override
			public void sucess(Object result){
//				AlertDialog.Builder ab = new AlertDialog.Builder(activity); 
//				ab.setMessage("삭제되었습니다.");					
//				ab.setPositiveButton("ok", null);  
//				ab.show();
				
				// 리스트 reflash
				showFolderEditList(null);				
			}
			
			@Override
			public void threadProcess(ConnectThread resultset) throws Exception {
				// TODO Auto-generated method stub					
				HttpClient client = NetWorkManager.getHttpConnection();    
				HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

				HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/delFolder.php");				
//				2.	parameter : 
//					a. uId : 유저ID b. fId : 폴더ID 
//				- Response
//				    1. type : plain ( 0 : 실패, 1 : 성공 ) 

				String buserId = activity.facebookMd.getBonoUserId();				
				if(buserId == null || folderId.length() < 1 || folderId == null || folderId.length() < 1){
					throw new Exception("parameter error");
				}				
				
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("uId", buserId));
				params.add(new BasicNameValuePair("fId", folderId));
				
//				Log.e("#########request", "########" + post.getURI().toURL());
//				Log.e("#########uId", "########" + params.get(0));
//				Log.e("#########fId", "########" + params.get(1));
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);  

				InputStream in = responsePOST.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{					
					str.append(line);
				}
				in.close();					
				String jsonStr = str.toString();
//				Log.e("#########result", "########" + jsonStr);
				
				if("0".equals(jsonStr)){
					throw new Exception("fail");
				}
				
			}
		}).start(); 
	}

	@Override
	public void backMd() {
		// TODO Auto-generated method stub
		activity.folderMd.showFolderList();
			
	}
}
